package com.ruoyi.common.utils.sednSms;

import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;

import java.util.HashMap;
import java.util.Map;

import static com.aliyun.teautil.Common.toJSONString;

public class SendSmsUtil {
    public static final String ALIBABA_CLOUD_ACCESS_KEY_ID = "LTAI5tMvRD3GmSvaHU4JUnnL";
    public static final String ALIBABA_CLOUD_ACCESS_KEY_SECRET = "MiLzrEACR8FeQgn4XMG2HlUNVe8nkY";

    public static Client createClient() throws Exception {
        Config config = new Config()
                // 配置 AccessKey ID，请确保代码运行环境设置了环境变量。
                .setAccessKeyId(ALIBABA_CLOUD_ACCESS_KEY_ID)
                // 配置 AccessKey Secret，请确保代码运行环境设置了环境变量。
                .setAccessKeySecret(ALIBABA_CLOUD_ACCESS_KEY_SECRET);
        // 配置 Endpoint
        config.endpoint = "dysmsapi.aliyuncs.com";

        return new Client(config);
    }

    /**
     * 发送短信
     *
     * @return
     * @throws Exception
     */
    public static JSONObject sendSms(String phone, Integer code) {
        try {
            Client client = createClient();
            Map<String, Object> map = new HashMap<>();
            map.put("code", code);
            String templateParam = toJSONString(map);
            // 构造请求对象，请填入请求参数值
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName("杭州禾生长天科技")
                    .setTemplateCode("SMS_476930166")
                    .setTemplateParam(templateParam);
            // 响应包含服务端响应的 body 和 headers
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            return JSONObject.parseObject(toJSONString(sendSmsResponse.getBody()));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
